#include "../log.h"
#include "mysqlconnectionpool.h"
#include "asyncservice.h"
#include "databaseservice.h"
#include <boost/bind.hpp>

DatabaseService::DatabaseService(AsyncService &service) :
    m_service(service)
{

}

DatabaseService::~DatabaseService()
{

}

bool DatabaseService::init(const std::string &db,
                           const std::string &host,
                           const std::string &user,
                           const std::string &password,
                           unsigned short port)
{
    m_pool = PoolPtr(new MysqlConnectionPool(db, host, user, password, port));

    if(!m_pool){
        return false;
    }

    return true;
}

void DatabaseService::serve(BOOST_ASIO_MOVE_ARG(Task) t)
{
    m_service.post
            (
                boost::bind
                (
                    &DatabaseService::execute,
                    this,
                    Task(t)
                )
            );
}

void DatabaseService::execute(Task t)
{
    mysqlpp::Connection *c = m_pool->safe_grab();

    if(!c){
        LOG_ERROR() << "Get mysql connection from pool failed!";

        return;
    }

    t(c);

    m_pool->release(c);
}


